package com.ruoyi.Amount.service.impl;

import com.ruoyi.Amount.domain.DTO.AddDTO;
import com.ruoyi.Amount.result.Result;
import com.ruoyi.Amount.service.AmountService;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.storeExpend.domain.StoreExpend;
import com.ruoyi.storeExpend.service.IStoreExpendService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
@Service
public class AmountServiceImpl implements AmountService {

    @Autowired
    private SysStoreMapper sysStoreMapper;
    @Autowired
    private IStoreExpendService iStoreExpendService;
    @Autowired
    public SysAgentMapper sysAgentMapper;

    @Autowired
    private SysUserMapper userMapper;



    /**
     * 商户充值
     *
     * @param addDTO
     * @return
     */
    @Transactional
    public synchronized AjaxResult storeAddAmount (AddDTO addDTO){
        //0.查询当前操作用户id，部门id
        Long userId = SecurityUtils.getUserId();
        Long deptId = SecurityUtils.getDeptId();


        //1.获取当前商户id
        Long storeId = addDTO.getStoreId();

        //2.查询要充值的商户是否存在
        SysStore store = sysStoreMapper.selectSysStoreById(storeId);
          // 2.1判断商户是否存在
        if (store == null) { // 检查返回的对象是否为null
            // 2.2 商户不存在，无法进行充值操作
            return AjaxResult.error("商户不存在，无法进行充值操作");
        }
        addDTO.setExchangeAmount(addDTO.getExchangeAmount().setScale(2, RoundingMode.DOWN));

        //0.查询当前商户部门id
        //应该是查询当前用户的部门对应的代理商 是否为该商铺的代理商id
        //查询对应的代理商对象
        if (deptId.equals(100l)) {
            //说明是管理端
            if(store.getAgentId()!=0) {
                return AjaxResult.error("无法进行充值操作");
            }

        }
        else {

            List<SysAgent> agents = sysAgentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息错误");
            }
            Long id = agents.get(0).getId();
            long storeDept = store.getAgentId();
            //0.判断商户部门id是否与当前用户部门id一致
            if (id != storeDept){
                //不相等，则返回错误
                return AjaxResult.error("无法进行充值操作");
            }

        }



       int rowsAffected= sysStoreMapper.updateSysBalance(addDTO.getStoreId(),addDTO.getExchangeAmount());



        // 4. 判断是否更新成功
        if (rowsAffected <= 0) {
            // 如果没有行被影响，说明更新失败
            return AjaxResult.error("增加金额失败");
        }

        //5.创建充值明细单
        //5.1 封装要提交的数据
        StoreExpend storeExpend = new StoreExpend();
        //拷贝传入的参数
        BeanUtils.copyProperties(addDTO,storeExpend);
        //记录的金额也是不四舍五入的
        storeExpend.setExchangeAmount(addDTO.getExchangeAmount());
        //生成交易标识id，十位数字和字母组成
        String ExchangeMark = getStringRandom(10);
        storeExpend.setExchangeMark(ExchangeMark);
        //授权类型为1商户
        storeExpend.setType(String.valueOf(1));

        storeExpend.setUserId(userId);
        storeExpend.setDeptId(deptId);

        storeExpend.setBalance(store.getBalance().add(addDTO.getExchangeAmount()));
        SysUser sysUser = userMapper.selectUserById(userId);
        if (deptId.equals(100l)) {
            storeExpend.setAgentId(0l);
            storeExpend.setAgentName("————————");
        }
        else {
            SysAgent sysAgent = sysAgentMapper.selectSysAgentById(store.getAgentId());

            storeExpend.setAgentId(sysAgent.getId());
            storeExpend.setAgentName(sysAgent.getName());
        }


        storeExpend.setContent("商户:"+store.getName()+"/类型:充值"+"/操作人:"+sysUser.getUserName());
        //5.2调用创建消费明细单

        iStoreExpendService.insertStoreExpend(storeExpend);

        // 如果到达这里，说明更新成功
        return AjaxResult.success("金额增加成功");

    }

    /**
     * 生成交易标识id，十位数字和字母组成
     *
     * @param length
     * @return
     */
    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();

        // 参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 代理商充值
     *
     * @param addDTO
     * @return
     */
    @Transactional
    public synchronized AjaxResult agentAddAmount (AddDTO addDTO){
        //0.查询当前操作用户的部门id

        Long userId = 1l;
        Long deptId = 100l;
        //判断当前用户部门id是否为100
        if (deptId!=100){
            //不是100，则表示不是管理端
            return AjaxResult.error("增加金额失败");
        }


        addDTO.setExchangeAmount(addDTO.getExchangeAmount().setScale(2, RoundingMode.DOWN));
        //1.获取当前代理商id
        Long agentId = addDTO.getAgentId();

        //2.查询要充值的代理商是否存在
        SysAgent agent = sysAgentMapper.selectSysAgentById(agentId);
        // 2.1判断商户是否存在
        if (agent == null) { // 检查返回的对象是否为null
            // 2.2 商户不存在，无法进行充值操作
            return AjaxResult.error("代理商不存在，无法进行充值操作");
        }

        // 3. 创建一个 SysAgent 对象，设置新的余额，并保留原有的代理商 ID
        SysAgent agentToUpdate = new SysAgent();
        agentToUpdate.setId(agentId); // 这里需要替换为你要更新的商户的 ID
        BigDecimal exchangeAmount = addDTO.getExchangeAmount();
        agentToUpdate.setBalance(exchangeAmount); // 把要增加的余额数量传过去  update sys_agent set balance =balance + 1.00000000 where id =3
        // 调用更新方法
        int rowsAffected = sysAgentMapper.updateSysAgentBalance(agentToUpdate);

        // 4. 判断是否更新成功
        if (rowsAffected <= 0) {
            // 如果没有行被影响，说明更新失败
            return AjaxResult.error("增加金额失败");
        }

        //5.创建充值明细单
        //5.1 封装要提交的数据
        StoreExpend storeExpend = new StoreExpend();
        //拷贝传入的参数
        BeanUtils.copyProperties(addDTO,storeExpend);

        //生成交易标识id，十位数字和字母组成
        String ExchangeMark = getStringRandom(10);
        storeExpend.setExchangeMark(ExchangeMark);
        //授权类型为1商户
        storeExpend.setType(String.valueOf(0));
        //查询修改后金额
        storeExpend.setUserId(SecurityUtils.getUserId());
        storeExpend.setDeptId(SecurityUtils.getDeptId());
//        storeExpend.setUserId(1l);
//        storeExpend.setDeptId(100l);
        //将充值后的余额写入明细表中

        storeExpend.setBalance(agent.getBalance());
        storeExpend.setDeptId(agent.getDeptId());
        storeExpend.setAgentName(agent.getName());
        //5.2调用创建消费明细单
        SysUser sysUser = userMapper.selectUserById(userId);
        storeExpend.setContent("代理商:"+agent.getName()+"/类型:充值"+"/操作人:"+sysUser.getUserName());

        iStoreExpendService.insertStoreExpend(storeExpend);

        // 如果到达这里，说明更新成功
        return AjaxResult.success("金额增加成功");

    }




}
